package com.centling.smartSealForPhone.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.activity.StampConfirmActivity;
import com.centling.smartSealForPhone.activity.StampDetailActivity;
import com.centling.smartSealForPhone.activity.StampListActivity;
import com.centling.smartSealForPhone.activity.StampTimeLimitActivity;
import com.centling.smartSealForPhone.adapter.RvStampListAdapter;
import com.centling.smartSealForPhone.bean.DetailBean;
import com.centling.smartSealForPhone.bean.DeviceTypeBean;
import com.centling.smartSealForPhone.bean.StampListBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.widget.AutoRecyclerView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * @author fionera
 */
public class StampListFragment
        extends TitleBarFragment {

    private EditText etInfo;

    private StampListBean stampListBean;
    private AutoRecyclerView rvStamp;
    private List<StampListBean.RowsEntity> stampList = new ArrayList<>();

    private PtrClassicFrameLayout ptrStampList;

    private int pageIndex = 0;

    private DeviceTypeBean deviceTypeBean;

    public static StampListFragment getInstance() {
        return new StampListFragment();
    }

    @Override
    public int setLayoutResource() {
        return R.layout.fragment_stamp_list;
    }

    @Override
    public void findViewInThisFunction(View rootView) {
        setTitleBarText("用印");
        setTitleBarLeft(R.drawable.ic_action_back);
        setTitleBarLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.finish();
            }
        });
        if (TextUtils.equals("1", SPUtil.getString(SPConstants.ENABLE_APP_PULL))) {
            setTitleBarRight(R.drawable.ic_action_add);
            setTitleBarRightClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShowDialog.showEditDialog(mContext, "输入流程码", "", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String applySn = (String) view.getTag();
                            if (TextUtils.isEmpty(applySn)) {
                                ShowToast.shortTime("请输入流程码");
                                return;
                            }
                            sendRequestToFetchInfo(applySn.trim());
                        }
                    });
                }
            });
        }

        initView(rootView);
        initData();
    }

    private void sendRequestToFetchInfo(final String applySn) {
        mProcessDialog.setTitle("正在获取用印信息").showNormal();
        getEnqueue(String.format(Locale.CHINA, UrlConstants.APPLY_DETAIL, applySn), new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();
                DetailBean bean = new Gson().fromJson(json, DetailBean.class);

                if (TextUtils.equals("1", bean.getSupplementApplyPicsFinalFlag()) && TextUtils
                        .equals("0", bean.getSupplementApplyPicsStatus())) {
                    startActivity(new Intent(mContext, StampConfirmActivity.class)
                            .putExtra("sealApplyId", applySn));
                } else {
                    startActivity(new Intent(mContext, StampDetailActivity.class)
                            .putExtra("sealApplyId", bean.getSealApplyId()));
                }
            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }

    private void initView(View view) {
        etInfo = view.findViewById(R.id.et_stamp_list_search_info);
        TextView tvSearch = view.findViewById(R.id.tv_stamp_list_search);
        ptrStampList = view.findViewById(R.id.ptr_stamp_list);
        rvStamp = view.findViewById(R.id.rv_stamp_list);

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etInfo.getText())) {
                    ShowToast.shortTime("请输入搜索的关键字！");
                } else {
                    InputMethodManager inputMethodService = (InputMethodManager) mContext.getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    if (inputMethodService != null) {
                        inputMethodService.hideSoftInputFromWindow(mActivity.getWindow().getDecorView().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    ((StampListActivity) mContext).changeFragment(
                            StampSearchFragment.getInstance(etInfo.getText().toString()), false,
                            R.id.ll_stamp_list);
                }
            }
        });
    }

    private void initData() {
        rvStamp.setLayoutManager(new GridLayoutManager(mContext, 1));
        RvStampListAdapter adapter = new RvStampListAdapter(mContext, stampList);
        rvStamp.setAdapter(adapter);
        adapter.setOnItemClickListener(new RvStampListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                StampListBean.RowsEntity rowsEntity = stampList.get(pos);
                if (TextUtils.equals("1", rowsEntity.getSupplementApplyPicsFinalFlag()) && TextUtils
                        .equals("0", rowsEntity.getSupplementApplyPicsStatus())) {
                    startActivity(new Intent(mContext, StampConfirmActivity.class)
                            .putExtra("sealApplyId", rowsEntity.getApplySn()));
                } else {
                    startActivity(new Intent(mContext, StampDetailActivity.class)
                            .putExtra("sealApplyId", stampList.get(pos).getSealApplyId()));
                }
            }
        });
        adapter.setOnButtonClickListener(new RvStampListAdapter.OnButtonClickListener() {
            @Override
            public void onButtonClick(View view, int pos, int type) {
                StampListBean.RowsEntity rowsEntity = stampList.get(pos);
                switch (type) {
                    case 0:
                        if (TextUtils.equals("1", rowsEntity.getSupplementApplyPicsFinalFlag()) && TextUtils
                                .equals("0", rowsEntity.getSupplementApplyPicsStatus())) {
                            startActivity(new Intent(mContext, StampConfirmActivity.class)
                                    .putExtra("sealApplyId", rowsEntity.getApplySn()));
                        } else {
                            sendRequestToCheckIsUse(rowsEntity, pos);
                        }
                        break;
                    case 1:
                        clickToStopStamp(rowsEntity.getSealApplyId());
                        break;
                    default:
                        break;
                }
            }
        });

        ptrStampList.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                sendRequestToGetStampList(true);
            }
        });

        rvStamp.setLoadDataListener(new AutoRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                sendRequestToGetStampList(false);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        ptrStampList.post(new Runnable() {
            @Override
            public void run() {
                ptrStampList.autoRefresh();
            }
        });
    }

    private void sendRequestToGetStampList(final boolean isRefresh) {
        if (isRefresh) {
            pageIndex = 0;
        }
        getEnqueue(String.format(Locale.CHINA, UrlConstants.STAMP_LIST, pageIndex),
                new OkHttpUtil.NetCallBack() {

                    @Override
                    public void onSucceed(String json) {
                        if (isRefresh) {
                            stampList.clear();
                            rvStamp.setLoadDataListener(new AutoRecyclerView.LoadDataListener() {
                                @Override
                                public void onLoadMore() {
                                    sendRequestToGetStampList(false);
                                }
                            });
                        }
                        stampListBean = new Gson().fromJson(json, StampListBean.class);
                        stampList.addAll(stampListBean.getRows());
                        rvStamp.getAdapter().notifyDataSetChanged();
                        if (stampListBean != null && stampListBean.getRows().size() < 20) {
                            rvStamp.loadMoreComplete(true);
                        } else {
                            rvStamp.loadMoreComplete(false);
                        }
                        ptrStampList.refreshComplete();
                        pageIndex++;
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime(reason);
                        ptrStampList.refreshComplete();
                        rvStamp.loadMoreComplete(false);
                    }
                });
    }

    private void sendRequestToGetTimes(final int pos) {
        mProcessDialog.setTitle("正在获取用印信息").showNormal();
        getEnqueue(String.format(Locale.CHINA, UrlConstants.GET_STAMP_REMAIN_TIMES_NEW, stampList.get(pos).getSealApplyId()),
                new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        mProcessDialog.dismiss();
                        Intent intent = new Intent(mContext, StampTimeLimitActivity.class);
                        intent.putExtra("sealApplyId", stampList.get(pos).getSealApplyId());
                        intent.putExtra("macAddress", stampList.get(pos).getSealEquipBlueToothMac());
                        intent.putExtra("equipSn", stampList.get(pos).getEmbenedSn());
                        intent.putExtra("sealApplyStartTime", stampList.get(pos).getApplyStartTimeReal());
                        intent.putExtra("sealApplyEndTime", stampList.get(pos).getApplyEndTimeReal());
                        mContext.startActivity(intent);
                    }

                    @Override
                    public void onFailed(String reason) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime(reason);
                    }
                });
    }

    private void sendRequestToCheckIsUse(final StampListBean.RowsEntity rowsBean, final int pos) {
        getEnqueue(String.format(Locale.CHINA, UrlConstants.GET_DEVICE_STATE_NEW + "?embenedSn=%s",
                GlobalData.USESEAL, rowsBean.getEmbenedSn()), new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                        if (deviceTypeBean.isAllowed()) {
                            clickToStamp(pos);
                        } else {
                            ShowToast.shortTime(deviceTypeBean.getMessage());
                        }
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime(reason);
                    }
                });
    }

    private void clickToStamp(int pos) {
        if (TextUtils.equals(stampList.get(pos).getApplyType(), "COUNT_LIMIT")) {
            Intent intent = new Intent(mContext, StampActivity.class);
            intent.putExtra("sealApplyId", stampList.get(pos).getSealApplyId());
            intent.putExtra("macAddress", stampList.get(pos).getSealEquipBlueToothMac());
            intent.putExtra("equipSn", stampList.get(pos).getEmbenedSn());
            mContext.startActivity(intent);
        } else {
            sendRequestToGetTimes(pos);
        }
    }

    private void clickToStopStamp(final String sealApplyId){
        ShowDialog.showSelectDialog(mContext, "警告", "确定将结束用印，剩余次数无法使用", "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> param = new HashMap<>();
                param.put("sealApplyId", sealApplyId);
                postJsonEnqueue(UrlConstants.STOP_STAMP, param, new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        sendRequestToGetStampList(true);
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime("提前结束用印失败，请重试");
                    }
                });
            }
        });
    }
}
